//
//  TS_MineViewController.swift
//  todaySwift
//
//  Created by ChokWah on 2018/3/5.
//  Copyright © 2018年 ChokWah. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class TS_MineViewController: UITableViewController {

    fileprivate let disposeBag = DisposeBag()
    var sections = [[MyCellModel]]() // 这里不能声明为可选类型，在tableview里面会crash
    var concerns = [MyConcern]()
    fileprivate lazy var headerView : NoLoginHeaderView = {
        let headerView = NoLoginHeaderView.loadViewFromNib()
        return headerView
    }()
    
    override var preferredStatusBarStyle: UIStatusBarStyle  {
        return .lightContent
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.tableHeaderView = headerView
        tableView.backgroundColor = UIColor.globalBackgroundColor()
        tableView.cwc_registerCell(cell: MyOtherCell.self)
        tableView.cwc_registerCell(cell: MyFirstSectionCell.self)
//        tableView.cwc_registerCell(cell: MyFirstSectionCell.self)
        // 获取数据
        NetWorkTool.loadMyCellData { (sections) in
            let string = "{\"text\":\"我的关注\",\"grey_text\": \"\"}"
            let myConcern = MyCellModel.deserialize(from: string)
            var myConcerns = [MyCellModel]()
            myConcerns.append(myConcern!)
            self.sections.append(myConcerns)
            self.sections += sections
            self.tableView.reloadData()
            NetWorkTool.loadMyConcern(completionHandler: { (concern) in
                self.concerns = concern
                print(concern)
                let indexSet = IndexSet(integer: 0)
                self.tableView.reloadSections(indexSet, with: .automatic)
            })
        }
        headerView.moreLoginButton.rx.controlEvent(.touchUpInside)
            .subscribe(onNext: { [weak self] in
                let storyboard = UIStoryboard(name: String(describing: MoreLoginViewController.self), bundle: nil)
                let moreVC = storyboard.instantiateViewController(withIdentifier: String(describing: MoreLoginViewController.self)) as! MoreLoginViewController
                moreVC.modalSize = (width: .full, height: .custom(size: Float(screenHeight - (isIPhoneX ? 44 : 0))))
                self!.present(moreVC, animated: true, completion: nil)
            }).disposed(by: disposeBag)
    }
}

// UITableView的方法都放这里
extension TS_MineViewController {
    
    // 每组头部的高度
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 1 ? 0 : 10
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y // 静止为-20
        print("滑动：\(offsetY)")
        if  offsetY < 0 {
            let totalOffset = kMyHeaderViewHeight + abs(offsetY)
            print("totalOffset：\(totalOffset)")

            let f = totalOffset / kMyHeaderViewHeight
            headerView.bgImageView.frame = CGRect(x: -screenWidth * (f - 1) * 0.5, y: offsetY, width: screenWidth * f, height: totalOffset)
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == 0 {
            return (concerns.count == 0 || concerns.count == 1) ? 40 : 114
        }
        return 40
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width:screenWidth , height: 10))
        view.backgroundColor = UIColor.globalBackgroundColor()
        return view
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].count
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let row = sections[indexPath.section]
        let myCellModel = row[indexPath.row]
        
        if indexPath.section == 0 && indexPath.row == 0 {
            let cell = tableView.cwc_dequeueReusableCell(indexPath: indexPath) as MyFirstSectionCell
            cell.myCellModel = myCellModel
            cell.myConcernSelected = { [weak self] (myConcern) in
                    let userDetailVC = UserDetailViewController()
                userDetailVC.user_id = myConcern.userid!
                self?.navigationController?.pushViewController(userDetailVC, animated: true)
            }
//            cell.delagate = self
            if concerns.count == 0 || concerns.count == 1 {
                cell.conectionView.isHidden = true
            }
            if concerns.count == 1 {
                cell.myConcern = concerns.first
            }
            if concerns.count > 1 {
                cell.myConcerns = concerns
            }
            return cell
        }
         
        let cell = tableView.cwc_dequeueReusableCell(indexPath: indexPath) as  MyOtherCell // 如果用带indexPath的方法，需要判断是否为nil，然后新建
        cell.leftLabel.text = myCellModel.text
        cell.rightLabel.text = myCellModel.grey_text
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 3 {
            if indexPath.row == 1 { // 跳转到设置界面
                let settingVC = SettingViewController()
                settingVC.navigationItem.title = "设置"
                navigationController?.pushViewController(settingVC, animated: true)
            }
        }
    }
}

//extension TS_MineViewController: MyFirstSectionCellDelegate {
//    func MyFirstSectionCell(_ firstCell: MyFirstSectionCell, myConcern: MyConcern) {
//        // 跳转到用户详情的VC
//        let userDetailVC = UserDetailViewController()
//        navigationController?.pushViewController(userDetailVC, animated: true)
//    }
//}

